package org.example.thymeleaf;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.util.StringUtils;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ThymeleafApplication {
    public static void main(String[] args) throws IOException {
        Map<String, Object> data = new HashMap<>();
        data.put("id", 1001L);
        data.put("name", "张三");
        data.put("url", "http://www.bing.com");
        data.put("createTime", new Date());
        data.put("hobbies", new String[]{"Basketball", "Football", "Pingpang"});
        System.out.println(data);
        String json = render(TemplateMode.TEXT, "templates/json/", "json-map", "obj", data, "test.json");
        System.out.println(json);

        String html = render(TemplateMode.HTML, "templates/html/", "user-map", "obj", data, null);
        System.out.println(html);
    }

    private static String render(TemplateMode mode, String resources, String templateId, String key, Object data, String targetFile) throws IOException {
        // 模板解析器
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        //模板所在目录，相对于当前classloader的classpath。
        resolver.setPrefix(resources);
        // 模板文件后缀
        if (mode == TemplateMode.HTML) {
            resolver.setSuffix(".html");
        } else {
            resolver.setSuffix(".tpl");
        }
        // 设置模式
        resolver.setTemplateMode(mode);
        // 模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(resolver);
        // 构造上下文
        Context context = new Context();
        context.setVariable(key, data);
        // 渲染模版，输出到文件流
        if (!StringUtils.isEmpty(targetFile)) {
            try (FileWriter writer = new FileWriter(targetFile)) {
                templateEngine.process(templateId, context, writer);
            }
        }
        // 渲染模板，直接输出内容
        String result = templateEngine.process(templateId, context);
        return result;
    }
}
